package com.djz.stuinfomge.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class LoginAct extends BaseAct{
	public String  page() {
		//System.out.println("LoginAct page");
		return "login";
	}
	
	public String doLogin(){
		System.out.println("---------doLogin");
		if(username == null && password ==null){
			msg = "用户名或密码错误，请重试！";
			return "login";
		}
		if(validateUser()){
			HttpSession session = ServletActionContext.getRequest().getSession();
			Map<String,Object> currUser = new HashMap<String, Object>();
			
			Object user = getUserByRole();
			
			currUser.put("user", user);
			currUser.put("role", role);
			session.setAttribute("currUser", currUser);
			return SUCCESS;
		
		}
		
		msg = "用户名或密码错误，请重试！";
		System.out.println("msg: "+ msg);
		return "login";
	}
	
	
	
	private Object getUserByRole() {
		String sql = null;
		if("admin".equals(role))
			sql = "from Administrator where name = ? and password = ?";
		else if("student".equals(role))
			sql = "from Student where name = ? and password = ?";
		else {
			sql = "from Teacher where name = ? and password = ?";
		}
		
		List list = ht.find(sql, username,password);
		
		return list.get(0);
	}

	private boolean validateUser() {
		String sql = null;
		if("admin".equals(role))
			sql = "select count(*) from Administrator where name = ? and password = ?";
		else if("student".equals(role))
			sql = "select count(*) from Student where name = ? and password = ?";
		else {
			sql = "select count(*) from Teacher where name = ? and password = ?";
		}
		
		List list = ht.find(sql, username,password);
		if((Long)list.get(0)>0)
			return true;
		
		return false;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}


	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}
@Autowired
	private	HibernateTemplate ht;
	
	private String msg;
	private String role;
	private String username;
	private String password;
}
